<template>
  <div class="flex-column bg-color-white width100 font-Regular" style="border-top: 1px solid #f2f2f2">
    <div class="container flex-between" style="padding: 20px 0">
      <div class="flex-column">
        <h5 class="course-title">{{ data.courseInfo.name }}</h5>
        <div class="flex-start-center" style="padding-top: 10px;font-size: 16px;color: #999999">
          <span>{{ data.courseInfo.validStartTime + '至' + data.courseInfo.validEndTime }}</span>
          <span style="margin-left: 5px">
              <span>剩余有效期</span>
              <span style="margin: 0 4px 0 7px;color: #e2503d">{{ daysBetween(data.courseInfo.validEndTime) }}</span>
              <span>天</span>
            </span>
          <span style="padding: 0 5px;font-size: 12px;color: #999999">|</span>
          <span style="margin-right: 10px">学习进度</span>
          <div style="width: 160px;margin-left: 10px">
            <el-progress :color="'#04addb'" :percentage="getCoursePercentage()"/>
          </div>
        </div>
      </div>
      <div style="margin-left: 180px;" v-if="data.courseInfo.freeFlag != 1">
        <el-button type="primary" @click="solveProblems" style="border-radius: 28px;margin-top: -4px;">去刷题</el-button>
      </div>
      <div>
        <div class="flex-start" style="font-size: 16px;color: #171920;font-weight: 400">
          <div class="flex-column flex-end" style="text-align: right">
            <span>{{ '距离' + examInfo.courseTypeName + '考试还有' }}</span>
            <p style="margin-top: 4px;justify-content: flex-end" class="flex-middle">
              <span class="color-theme" style="font-size: 24px">{{ daysBetween(examInfo.examStartDate) }}</span>
              <span style="margin-left: 4px;color:#171920;">天</span>
            </p>
          </div>
          <div class="change-select-area">
            <div>
              <div class=" click  tw-relative tw-w-66" style="margin-left: 20px;display: flex;justify-content: flex-end;align-items: center"
                   @click="changsAreaClick" v-click-outside="onClickOutside" @mouseleave="startCarousel"
                   @mouseover="stopCarousel">
                <el-icon :color="areaChange?'#04addb':'#666666'" size="16">
                  <Location/>
                </el-icon>
                <span :style="{color:areaChange?'#04addb':'#666666'}"
                >{{ data.currentArea.name }}</span>
                <select-area-dropdown
                    ref="areaDropDown"
                    :areaTypeList="data.areaTypeArr"
                    :currentArea="data.currentArea"
                    left="-180px"
                    top="36px"
                    @changeArea="getCourseConfig"
                ></select-area-dropdown>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {Location} from '@element-plus/icons-vue'
import {defineProps, getCurrentInstance, onMounted, reactive, ref, watch} from "vue";
import {useRoute, useRouter} from 'vue-router';
import {getMyCourseDetail} from '@/api/study.js'
import {daysBetween, formatNumber} from '@/utils/common.js'
import SelectAreaDropdown from "@/views/course/component/select-area-dropdown.vue";
import {getTreeDictByCode} from "@/api/home.js";
import { doExerciseExercise } from '../../../api/study';

const props = defineProps({
  courseId: {
    type: Number,
    default: ''
  },
  orderItemId: {
    type: Number,
    default: ''
  },
  examInfo: {
    type: Object,
    default: {}
  },
});
onMounted(() => {
  getArea()
})
const route = useRoute();
const router = useRouter();
const {proxy} = getCurrentInstance();

const emits = defineEmits(['closeDialog', 'getCourseConfig'])

const data = reactive({
  courseInfo: {
    id: '',
    orderItemId: '',
    courseTypeId: '',
    name: '',
    validStartTime: '',
    validEndTime: '',
    finishLessonCount: '',
    lessonCount: '',
    provinceName: '',
    mockBankId: '',
    freeFlag:''
  },
  areaTypeArr: [],//省市数组
  currentArea: {}//当前选择省份
})

function initData() {
  getCourseDetail()
}

function getCourseDetail() {
  let requestData = {
    courseId: data.courseInfo.id,
    orderItemId: data.courseInfo.orderItemId
  }
  getMyCourseDetail(requestData, (res) => {
    Object.keys(data.courseInfo).forEach((key) => {
      data.courseInfo[`${key}`] = res.data[`${key}`]
    })
    data.courseInfo.provinceName = localStorage.getItem('provinceName')
    data.courseInfo.courseTypeId = props.courseTypeId
  })
}

const getCoursePercentage = () => {
  return formatNumber((data.courseInfo.finishLessonCount / data.courseInfo.lessonCount) * 100)
}
const getArea = () => {
  getTreeDictByCode({typeCode: "regionCode"}, (res) => {
    data.areaTypeArr = res.data;
    let index = res.data.findIndex(item => item.name == localStorage.getItem('provinceName'))
    if (index >= 0) {
      data.currentArea = res.data[index]
    } else {
      data.currentArea = res.data[0]
    }
    getCourseConfig(data.currentArea)
  });
}
watch(() => props.courseId, (val) => {
  data.courseInfo.id = val
  data.courseInfo.orderItemId = props.orderItemId
  initData()
})
watch(() => props.examInfo, (val) => {
})
let areaChange = ref(false)
const stopCarousel = () => {
  areaChange.value = true
}
const startCarousel = () => {
  areaChange.value = false
}
const getCourseConfig = (province) => {
  data.currentArea = province
  emits('getCourseConfig', province)
}

// 监听是否点击弹窗外部
let areaDropDown = ref()
const changsAreaClick = () => {
  areaDropDown.value.openAreaDialog(2)
}
const vClickOutside = {
  mounted(el, binding) {
    const eventHandler = (e) => {
      if (!el.contains(e.target)) {
        if (typeof binding.value === 'function') {
          binding.value(e);
        }
      }
    };
    el.__click_outside__ = eventHandler;
    document.addEventListener('click', eventHandler);
  },
  beforeUnmount(el) {
    document.removeEventListener('click', el.__click_outside__);
    delete el.__click_outside__;
  }
}
const onClickOutside = () => {
  areaDropDown.value.openAreaDialog(1)
}

const solveProblems = () => {
  if(data.courseInfo.mockBankId){
    let allData = {
      courseId: data.courseInfo.id,
      orderItemId:props.orderItemId,
      bankId: data.courseInfo.mockBankId,
  }
  doExerciseExercise(allData, res => {
      window.open(res.data)
    })
  }else{
    proxy.$message.warning('题库正在上架中...')
  }
}
</script>
<style lang="scss" scoped>
.course-title {
  font-size: 24px;
  font-weight: 500;
  color: #171920;
}

.live-button {
  width: 86px;
  font-size: 14px;
  padding: 9px 13px;
  font-weight: 500;
  border-radius: 30px;
  border: 1px #E2E2E2 solid;
  text-align: center;
  align-content: center;
}

.change-select-area:hover .select-area {
  display: block;
}

</style>

